package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * @Author: zcm
 * @CreateTime: 2025-10-16  15:46
 * @Description: Redis分布式锁
 * @Version: 1.0
 */
public class SimpleRedisLock implements ILock {

    private static final String KEY_PREFIX = "lock:";
    private static final String VALUE_PREFIX = UUID.randomUUID().toString(true) + "-";
    private StringRedisTemplate stringRedisTemplate;
    private String name;

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 获取锁
     *
     * @param timeoutSecond 过期时间
     * @return true || false
     */
    @Override
    public boolean tryLock(long timeoutSecond) {
        Boolean getLock = stringRedisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + name, VALUE_PREFIX + Thread.currentThread().getId()
                        , timeoutSecond, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(getLock);
    }

    /**
     * 释放锁
     */
    @Override
    public void unLock() {
        String redisValue = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        String expectValue = VALUE_PREFIX + Thread.currentThread().getId();
        // 判断锁标志是否一致
        if (redisValue.equals(expectValue)){
            stringRedisTemplate.delete(KEY_PREFIX + name);
        }
    }
}
